﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Web.SessionState;
using System.Data;
using Newtonsoft.Json;
using Framework.DataAccess;
using Framework.Common.JsonEntities;
using Framework.Common;
using Framework.Common.Common;
using Mode;

namespace WebSite.WebServer
{
    /// <summary>
    /// MOdelManage 的摘要说明
    /// </summary>
    public class ModelManage : IHttpHandler, IRequiresSessionState
    {
        JsonReturnMessages msg;
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            msg = new JsonReturnMessages();
            try
            {
                string action = context.Request.Params["Action"];
                if (action == "AreRoleTree")
                    AreRoleTree();
                else if (action == "ModelGrid")
                    GetAreRoleModel();
                else if (action == "SwitchModel")
                    SwitchModelStatus();
                else if (action == "CountTopicByType")
                    CountTopicByType();
                else if (action == "AddModel")
                    AddModel();
                else if (action == "ModelRoleTopicList")
                    GetModelRoleTopicList();
                else if (action == "AddManualModel")
                    AddManualModel();
                else if (action == "ManualModelDetList")
                    GetManualModelDetList();
                else if (action == "RandomModelDetList")
                    GetRandomModelDetList();
            }
            catch (Exception err)
            {
                var message = err.Message;
                if (err.InnerException != null && err.InnerException.Message != null)
                    message += "<BR>" + err.InnerException.Message;

                msg.IsSuccess = 0;
                msg.Msg = message;

                var json = JsonConvert.SerializeObject(msg);
                context.Response.Write(json);
            }
            context.Response.End();
        }

        private loginInfo chklogin()
        {
            try
            {
                return SessionShard.loginUser;
            }
            catch
            {
                msg.IsSuccess = -9;
                msg.Msg = "登陆失效，请重新登陆!";
                return null;
            }
        }

        // 获取区域角色树
        void AreRoleTree()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo loginUser = chklogin();
            if (loginUser == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(msg));
                return;
            }

            AreRoleTree art = new AreRoleTree(loginUser.A_ID);
            string v = art.ToJson(true);

            context.Response.Write(v);
        }

        // 获取区域,角色下的模型.
        void GetAreRoleModel()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo loginUser = chklogin();
            if (loginUser == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(msg));
                return;
            }


            int areid = context.Request.Params["aid"].ToInt();
            int? roleid = context.Request.Params["rid"].ToInt();

            int typeID = context.Request.Params["type"].ToInt();
            DateTime? beginDate = context.Request.Params["beginDate"].ToDateNull();
            DateTime? endDate = context.Request.Params["endDate"].ToDateNull();
            string title = context.Request.Params["title"].ToStr();
            int status = context.Request.Params["status"].ToInt();

            PageView pageInfo = new PageView();
            pageInfo.PageIndex = context.Request.Params["page"].ToInt(1);
            pageInfo.PageSize = context.Request.Params["pagesize"].ToInt(20);
            pageInfo.SortName = context.Request.Params["sortname"].ToStr();
            pageInfo.SortOrder = context.Request.Params["sortorder"].ToStr();
            pageInfo.SearchParams = context.Request.Params;

            //如果不是超级管理员，则将区域ID设置成登录的区域ID
            if (loginUser.A_LEVEL != 0 || loginUser.R_POWER != 1)
                areid = loginUser.A_ID;

            ModeAdpater ma = new ModeAdpater();
            PageList<object> List = ma.GetGridJson(pageInfo, status, typeID, areid, (roleid == -1 ? null : roleid), beginDate, endDate, title);
            string Rjson = @"{""Rows"":null,""Total"":""0""}";
            if (List.Data != null)
            {
                Rjson = @"{""Rows"":" + List.Data.ToJson() + @",""Total"":""" + List.Total + @"""}";
            }

            context.Response.Write( Rjson );
        }

        // 启停用模型
        void SwitchModelStatus()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo loginUser = chklogin();
            if (loginUser == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(msg));
                return;
            }

            int modelid = context.Request.Params["modelid"].ToInt(0);
            int status = context.Request.Params["status"].ToInt(0);

            ModeAdpater ma = new ModeAdpater();
            bool succFlag = ma.SetModelStatus(modelid, status);
            if (succFlag)
                msg.IsSuccess = 1;
            var json = JsonConvert.SerializeObject(msg);

            context.Response.Write(json);

        }

        /// <summary>
        /// 获取数量
        /// </summary>
        private void CountTopicByType()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo loginUser = chklogin();
            if (loginUser == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(msg));
                return;
            }
            int roleID = context.Request.Params["roleID"].ToInt(0);
            int? topicType = context.Request.Params["topicType"].ToIntNull();
            Topic myTopic = new Topic();
            int roleCount = myTopic.CountRoleTopic(0, roleID, topicType);
            int publicCount = myTopic.CountRoleTopic(1, roleID, topicType);
            var json = JsonConvert.SerializeObject(new {roleCount=roleCount, publicCount=publicCount });
            context.Response.Write(json);
        }

        /// <summary>
        /// 保存模型数据
        /// </summary>
        private void AddModel()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo loginUser = chklogin();
            if (loginUser == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(msg));
                return;
            }
            string str = context.Request.Params["modelData"];
            model_table modelData = JsonConvert.DeserializeObject<model_table>(str);
            str = context.Request.Params["modelDetList"];
            List<compute_table> modelDetList = JsonConvert.DeserializeObject<List<compute_table>>(str);
            str = context.Request.Params["areRoleIDs"].ToStr();
            string[] ids = str.TrimEnd(',').Split(',');
            List<int> areRoleList = new List<int>();
            foreach (string strID in ids)
            {
                int areRole;
                if (int.TryParse(strID, out areRole))
                    areRoleList.Add(areRole);
            }
            ModeAdpater myModel = new ModeAdpater();
            int id = myModel.AddModel(modelData, modelDetList, areRoleList);
            if (id > 1)
            {
                msg.Data = id;
                msg.IsSuccess = 1;
            }
            else
            {
                msg.IsSuccess = 0;
                msg.Msg = "保存数据失败！";
            }
            var json = JsonConvert.SerializeObject(msg);
            context.Response.Write(json);
        }

        /// <summary>
        /// 保存手动模型数据
        /// </summary>
        private void AddManualModel()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo loginUser = chklogin();
            if (loginUser == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(msg));
                return;
            }
            string str = context.Request.Params["modelData"];
            model_table modelData = JsonConvert.DeserializeObject<model_table>(str);
            str = context.Request.Params["modelDetList"];
            //先获取手动模型数据,在转换成具体的题目ID
            List<compute_manual_table> modelDetList = JsonConvert.DeserializeObject<List<compute_manual_table>>(str);
            List<compute_table> modelTopicList = new List<compute_table>();
            foreach (compute_manual_table mt in modelDetList)
            {
                string[] strTopicIDs = mt.topicIDStrs.TrimEnd(',').TrimStart(',').Split(',');
                foreach (string strID in strTopicIDs)
                {
                    int topicID;
                    if (int.TryParse(strID, out topicID))
                    {
                        modelTopicList.Add(new compute_table() { model = mt.model, publiccount = 0, rolecount = 0, topic = topicID, score = mt.score, type = mt.type });
                    }
                }
            }
            //区域角色
            str = context.Request.Params["areRoleIDs"].ToStr();
            string[] ids = str.TrimEnd(',').Split(',');
            List<int> areRoleList = new List<int>();
            foreach (string strID in ids)
            {
                int areRole;
                if (int.TryParse(strID, out areRole))
                    areRoleList.Add(areRole);
            }

            ModeAdpater myModel = new ModeAdpater();
            int id = myModel.AddModel(modelData, modelTopicList, areRoleList);
            if (id > 1)
            {
                msg.Data = id;
                msg.IsSuccess = 1;
            }
            else
            {
                msg.IsSuccess = 0;
                msg.Msg = "保存数据失败！";
            }
            var json = JsonConvert.SerializeObject(msg);
            context.Response.Write(json);
        }


        /// <summary>
        /// 手动选题时获取角色题型的题目列表
        /// </summary>
        public void GetModelRoleTopicList()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo loginUser = chklogin();
            if (loginUser == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(msg));
                return;
            }
            Topic topic = new Topic();

            int typeID = context.Request.Params["typeID"].ToInt(0);
            int roleID = context.Request.Params["roleID"].ToInt(0);

            PageView pageInfo = new PageView();
            pageInfo.PageIndex = context.Request.Params["page"].ToInt(1);
            pageInfo.PageSize = context.Request.Params["pagesize"].ToInt(20);
            pageInfo.SortName = context.Request.Params["sortname"].ToStr();
            pageInfo.SortOrder = context.Request.Params["sortorder"].ToStr();
            pageInfo.SearchParams = context.Request.Params;
            pageInfo.Fields = "T_ID,T_TITLE,T_DATE,R_NAME";


            PageList<object> List = topic.GetModelRoleTopicList(pageInfo, typeID, roleID);

            string Rjson = @"{""Rows"":null,""Total"":""0""}";
            if (List.Data != null)
            {
                Rjson = @"{""Rows"":" + List.Data.ToJson() + @",""Total"":""" + List.Total + @"""}";
            }
            context.Response.Write(Rjson);
        }

        /// <summary>
        /// 获取随机模型的题型列表
        /// </summary>
        public void GetRandomModelDetList()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo loginUser = chklogin();
            if (loginUser == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(msg));
                return;
            }
            PageView pageInfo = new PageView();
            pageInfo.PageIndex = context.Request.Params["page"].ToInt(1);
            pageInfo.PageSize = context.Request.Params["pagesize"].ToInt(20);
            pageInfo.SortName = context.Request.Params["sortname"].ToStr();
            pageInfo.SortOrder = context.Request.Params["sortorder"].ToStr();
            pageInfo.SearchParams = context.Request.Params;

            ModeAdpater myModel = new ModeAdpater();
            int modelID = context.Request.Params["modelID"].ToInt(0);
            PageList<object> List = myModel.GetRandomModelDetList(pageInfo, modelID);
            string Rjson = @"{""Rows"":" + List.Data.ToJson() + @",""Total"":""" + List.Total + @"""}";
            context.Response.Write(Rjson);
        }

        /// <summary>
        /// 获取手动模型的题型列表
        /// </summary>
        public void GetManualModelDetList()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo loginUser = chklogin();
            if (loginUser == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(msg));
                return;
            }
            PageView pageInfo = new PageView();
            pageInfo.PageIndex = context.Request.Params["page"].ToInt(1);
            pageInfo.PageSize = context.Request.Params["pagesize"].ToInt(20);
            pageInfo.SortName = context.Request.Params["sortname"].ToStr();
            pageInfo.SortOrder = context.Request.Params["sortorder"].ToStr();
            pageInfo.SearchParams = context.Request.Params;

            ModeAdpater myModel = new ModeAdpater();
            int modelID = context.Request.Params["modelID"].ToInt(0);
            PageList<object> List = myModel.GetManualModelDetList(pageInfo, modelID);
            string Rjson = @"{""Rows"":" + List.Data.ToJson() + @",""Total"":""" + List.Total + @"""}";
            context.Response.Write(Rjson);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}